import { JsonAsset, misc, sys, Vec2, Vec3 } from "cc";
import { ResourceManager } from "./ResourceManager";
import { httpRequest } from "./third-party-plugins/HttpRequest";

export const twoPointDegree = (startPos: Vec2, endPos: Vec2) => {
    const dirVec = endPos.subtract(startPos); //获得从startPos指向endPos的方向向量
    const comVec = new Vec2(1, 0); //计算夹角的参考方向，这里选择x轴正方向
    const radian = dirVec.signAngle(comVec); //获得带方向的夹角弧度值(参考方向顺时针为正值，逆时针为负值)
    const degree = Math.floor(misc.radiansToDegrees(radian));
    return -degree;
};

export const saveData = (textToWrite: string, fileNameToSaveAs: string) => {
    if (sys.isBrowser) {
        saveForBrowser(textToWrite, fileNameToSaveAs);
    } else {
        var writeable_path = jsb.fileUtils.getWritablePath();
        console.log(writeable_path);
        saveDataToFile(textToWrite, writeable_path + fileNameToSaveAs);
    }
};

export const readData = async (fileName: string, ext: string) => {
    if (sys.isBrowser) {
        const mapDataJson: JsonAsset = await ResourceManager.getInstance().loadPath("cfg/" + fileName);
        const mapData: any = mapDataJson.json;
        return mapData;
    } else {
        var writeable_path = jsb.fileUtils.getWritablePath();
        const fileNameWithExt = fileName + ext;
        const dataStr = readDataFromFile(writeable_path + fileNameWithExt);
        return dataStr ? JSON.parse(dataStr) : "";
    }
};

// 保存字符串内容到文件。
// 效果相当于从浏览器下载了一个文件到本地。
// textToWrite - 要保存的文件内容
// fileNameToSaveAs - 要保存的文件名
export const saveForBrowser = (textToWrite: string, fileNameToSaveAs: string) => {
    if (sys.isBrowser) {
        console.log("浏览器");
        let textFileAsBlob = new Blob([textToWrite], { type: "application/json" });
        let downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.innerHTML = "Download File";
        if (window.webkitURL != null) {
            // Chrome allows the link to be clicked
            // without actually adding it to the DOM.
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        } else {
            // Firefox requires the link to be added to the DOM
            // before it can be clicked.
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            // downloadLink.onclick = destroyClickedElement;
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    }
    // axios({
    //     method: "POST",
    //     url: `http://localhost:7457/cast-config.json`,
    //     data: textToWrite,
    //     timeout: 3000,
    // });
    // httpRequest.post(`http://localhost:7457/test.json`, { data: textToWrite });
};

export const saveDataToFile = (data: string, path: string) => {
    // 要在可写的路径先创建一个文件夹
    // 路径也可以是 外部存储的路径，只要你有可写外部存储的权限;
    // getWritablePath这个路径下，会随着我们的程序卸载而删除,外部存储除非你自己删除，否者的话，卸载APP数据还在;
    console.log("save data to file", path);
    jsb.fileUtils.writeStringToFile(data, path);
};

export const readDataFromFile = (path: string) => {
    // 要在可写的路径先创建一个文件夹
    // 路径也可以是 外部存储的路径，只要你有可写外部存储的权限;
    // getWritablePath这个路径下，会随着我们的程序卸载而删除,外部存储除非你自己删除，否者的话，卸载APP数据还在;
    if (jsb.fileUtils.isFileExist(path)) {
        console.log("exist file", path);

        return jsb.fileUtils.getStringFromFile(path);
    } else {
        console.log("not exist file", path);
        return "";
    }
};

// export const readFile = (filePath: string) => {
//     fs.readFile(filePath, "utf8", (err: any, data: any) => {
//         if (err) {
//             console.error(err);
//             return;
//         }
//         return data;
//     });
// };

// export const writeFile = (path: string, data: any): Promise<void> => {
//     return new Promise((resolve, reject) => {
//         fs.writeFile(path, data, (err: any) => {
//             if (err) {
//                 reject(err);
//             } else {
//                 resolve();
//             }
//         });
//     });
// };

// export const readFileSync = (filePath: string) => {
//     const data = fs.readFileSync(filePath, "utf8");
//     return data;
// };

// export const listFileInFolder = (folderName: string) => {
//     const arr = fs.readdirSync(folderName);
//     const fileList: string[] = [];
//     arr.forEach((file: string) => {
//         // var fullpath = path.join(folderName, file);
//         // var stats = fs.statSync(fullpath);
//         // if (stats.isDirectory()) {
//         //     listFileInFolder(fullpath);
//         // } else {
//         //     fileList.push(file);
//         // }
//     });
//     // console.log("fileList:", fileList);

//     return fileList;
// };
